#!/usr/bin/env python
import time
import random
import Dice as dice

dice.init()
clicks = 0
turns = 3

class Player(object):
  def __init__(self,name):
    self.name = name
    self.wins = 0
    self.points = 0
  
  def add_points(self, number):
    self.points = self.points + number
    
  def get_points(self):
    return self.points
    
  def set_points(self, number):
    self.points = number

  def add_wins(self):
    self.wins = self.wins + 1

  def get_wins(self):
    return self.wins
    
  def get_name(self):
    return self.name

def get_clicks():
  # waiting for first click
  while not dice.get_switch():
    time.sleep(0.05)
  state = True
  prev_state = True
  clicks = 1
  first_click = time.time()
  # 0.3 seconds to do another click
  while time.time() < first_click + 0.3:
    prev_state = state
    state = dice.get_switch()
    # GPIO Input rising slope
    if state and not prev_state:
      clicks = clicks + 1
    time.sleep(0.015)
  return clicks

def roll_dice():
  # to generate a more realistic impression of a rolling dice, the pidget
  # shows i different numbers
  i = random.randint(10,20)
  for k in range(i):
    # rolling: dice makes a circular count from 1 to 6 and stops after i steps
    number = k%6 + 1
    dice.set_dice(number)
    # rolling becomes slower as k increases
    time.sleep(0.015*k)
  return number

print('********** Welcome to Black Jack **********')

raspi = Player('Raspi')
name = input('\nPlease enter your name: ')
player = Player(name)

print('\n****************** Start ******************')

for i in range (0,turns):
  print('\nPlayer ' + player.get_name() + ' press switch to roll dice\n')
  clicks = get_clicks()
  while clicks < 2 and player.get_points() <= 21:
    if clicks == 1:
      number = roll_dice()
      player.add_points(number)
      print(player.get_name() + ' has ' + str(player.get_points()) + ' points.')
    clicks = get_clicks()
      
  if player.get_points() < 21:
    print()
    dice.set_dice(0)
    time.sleep(1)
    while raspi.get_points() <= player.get_points():
      number = roll_dice()
      raspi.add_points(number)
      print(raspi.get_name() + ' has ' + str(raspi.get_points()) + ' points.')
      time.sleep(2)
  
  if player.get_points() == 21 or raspi.get_points() > 21:
    print('\n' + player.get_name() + ' wins!')
    player.add_wins()
  elif player.get_points() > 21 or raspi.get_points() > player.get_points():
    print('\n' + raspi.get_name() + ' wins!')
    raspi.add_wins()
  print('Score:')
  print(player.get_name() + ': ' + str(player.get_wins()))
  print(raspi.get_name() + ': ' + str(raspi.get_wins()) + '\n')
    
  clicks = 0
  dice.set_dice(0)
  player.set_points(0)
  raspi.set_points(0)
if player.get_wins()>raspi.get_wins():
  print('Congratulations, you won!')
else:
  print('I am sorry, you lost!')
